package com.iven.xie.redis.service.impl;

import com.google.common.collect.Lists;
import com.iven.xie.redis.beans.DbDataInfo;
import com.iven.xie.redis.beans.RedisConfig;
import com.iven.xie.redis.service.DataService;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import java.math.BigDecimal;
import java.util.List;
import java.util.Set;

/**
 * @author xiezhendong
 * @data 2021/7/26
 */
@Service
public class DataServiceImpl implements DataService {
    @Override
    public List<DbDataInfo> getDbList(RedisConfig config) {

        List<DbDataInfo> dbDataList = Lists.newArrayList();

        Jedis jedis = null;
        try {
            jedis = new Jedis(config.getHost(), config.getPort(), config.getTimeOut());
            for (int i = 0; i < 16; i++) {
                jedis.select(i);
                Set<String> keys = jedis.keys("*");

                DbDataInfo dbDataInfo = new DbDataInfo();
                dbDataInfo.setIndex(i);
                dbDataInfo.setKeySize(BigDecimal.valueOf(keys.size()));
                dbDataInfo.setKeys(keys);
                dbDataList.add(dbDataInfo);
            }
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }

        return dbDataList;
    }
}
